package io.github.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import io.github.annotation.Log;
import io.github.entity.SysCallogsEntity;
import io.github.entity.SysPageEntity;
import io.github.entity.SysUserEntity;
import io.github.service.SysCalllogsService;
import io.github.util.ExcelUtil;
import io.github.util.PageUtils;
import io.github.util.R;
import org.apache.commons.lang3.StringUtils;
import org.hyperic.sigar.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author: weil
 * @date: 2019/9/18 20:27
 * @version: 1.0
 * @description:
 */
@Controller
@RequestMapping("/admin/sys/logs")
public class SysCalllogsController extends AbstractController {

    @Resource
    private SysCalllogsService sysCalllogsService;

    /**
     * 所有通话记录列表
     */
    @RequestMapping("/list")
    @ResponseBody
    @Log(value="录音记录查询",action = 0)
    public R list(@RequestBody JSONObject jsonObject) {
        logger.info("录音记录请求");
        String sort = "id";
        //获取当前登录用户
        SysUserEntity userEntity = getAdmin();
        //判断用户是否为炒鸡管理员
        String admin = userEntity.getUsername();

        Integer limit = jsonObject.getInteger("limit");
        String startTime = jsonObject.getString("startTime");   //开始时间
        String endTime = jsonObject.getString("endTime");       //结束时间
        String caller = jsonObject.getString("caller");         //主叫号码
        String callee = jsonObject.getString("callee");         //被叫号码
        String callerBelong = jsonObject.getString("callerBelong");  //主叫归属
        String calleeBelong = jsonObject.getString("calleeBelong");  //被叫归属
        String calleeTransfer = jsonObject.getString("calleeTransfer");  //被叫变换号码



        int offset = jsonObject.getInteger("offset");
        // 排序逻辑
        Boolean flag = null;
        if (StringUtils.isNoneBlank(jsonObject.getString("order"))) {
            if ("asc".equalsIgnoreCase(jsonObject.getString("order"))) {
                flag = true;
            } else {
                flag = false;
            }
        }
        PageUtils pageUtil = null;
        Page<SysCallogsEntity> adminList = sysCalllogsService.queryListByPage2(offset, limit,startTime,endTime,caller, flag,callee,callerBelong,calleeBelong,calleeTransfer);

        pageUtil = new PageUtils(adminList.getRecords(), adminList.getTotal(), adminList.getSize(), adminList.getCurrent());

        return R.ok().put("page", pageUtil);
    }

    @ResponseBody
    @RequestMapping("/callList")
    public R callList(@RequestBody JSONObject jsonObject) {
        String sort = "id";
        //获取当前登录用户
        SysUserEntity userEntity = getAdmin();
        //判断用户是否为炒鸡管理员
        String admin = userEntity.getUsername();

        int offset = jsonObject.getInteger("offset");
        // 排序逻辑
        Boolean flag = null;
        if (StringUtils.isNoneBlank(jsonObject.getString("order"))) {
            if ("asc".equalsIgnoreCase(jsonObject.getString("order"))) {
                flag = true;
            } else {
                flag = false;
            }
        }
        PageUtils pageUtil = null;
        Page<SysCallogsEntity> adminList = sysCalllogsService.queryListByPage(offset, jsonObject.getInteger("limit"),jsonObject.getString("sort"),jsonObject.getString("startTime"),jsonObject.getString("endTime"),jsonObject.getString("caller"), flag,jsonObject.getString("callee"));

        pageUtil = new PageUtils(adminList.getRecords(), adminList.getTotal(), adminList.getSize(), adminList.getCurrent());

        return R.ok().put("page", pageUtil);
    }

    @RequestMapping("/property")
    @ResponseBody
    public R getProperty() throws SigarException {
        Sigar sigar = new Sigar();
        CpuInfo infos[] = sigar.getCpuInfoList();
        CpuPerc cpuPerc[] = sigar.getCpuPercList();

        List listInfo = new ArrayList();
        List listInfo2 = new ArrayList();

        for(int i =0;i<infos.length;i++){
            CpuInfo info = infos[i];
            CpuPerc perc = cpuPerc[i];
            Map mapInfo = new HashMap();
            mapInfo.put("编号","第"+(i+1)+"块cpu");
            mapInfo.put("CPU类别",info.getModel());
            mapInfo.put("CPU缓存数量",info.getCacheSize());
            mapInfo.put("CPU系统使用率",CpuPerc.format(perc.getSys()));
            mapInfo.put("CPU当前错误率",CpuPerc.format(perc.getNice()));
            mapInfo.put("CPU总的使用率",CpuPerc.format(perc.getCombined()));

            listInfo.add(mapInfo);
        }

        Sigar sigar2 = new Sigar();
        FileSystem fslist[] = sigar2.getFileSystemList();
        for(int i = 0;i<fslist.length;i++){
            FileSystem fs = fslist[i];
            Map mapInfo = new HashMap();
            mapInfo.put("名称",fs.getDevName());
            mapInfo.put("盘符标志",fs.getFlags());
            mapInfo.put("盘符文件系统类型",fs.getType());

            try{
                FileSystemUsage usage = sigar2.getFileSystemUsage(fs.getDirName());
                mapInfo.put("总大小",usage.getTotal());
                mapInfo.put("剩余大小",usage.getFree());
                mapInfo.put("可用大小",usage.getAvail());
                mapInfo.put("资源的利用率",usage.getUsePercent() * 100D+"%");
            }catch(Exception e){
                System.out.println("******max***");
            }
            listInfo2.add(mapInfo);
        }

        return R.ok().put("cpu",listInfo).put("disk",listInfo2);
    }


    @RequestMapping("/number")
    @ResponseBody
    public R getNumber(){
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1;
        Map map = new HashMap();
        JSONArray array = new JSONArray();
        for(int i=0;i<12;i++){
            String tempTime;
            if(month>9){
                tempTime = year + "-"+month;
            }else{
                tempTime = year+"-0"+month;
            }
            Long sum = sysCalllogsService.getNumber(tempTime);
            JSONObject object = new JSONObject();
            object.put("name",tempTime);
            object.put("value",sum);
            array.add(object);
//            map.put(tempTime,sum);
            if(month==1){
                month = 12;
                year = year -1;
            }else{
                month = month-1;
            }


        }
        return R.ok().put("data",array);
    }

    /**
     * 下载录音
     */

    /**
     * 导出数据
     */
    @Log(value="录音记录导出",action = 7)
    @RequestMapping("/export")
    //@RequiresPermissions("sys:logs:export")
    @ResponseBody
    public void export(HttpServletResponse response) throws Exception {

        List<SysCallogsEntity> list = sysCalllogsService.queryAllLogs();

        response.setHeader("Content-disposition","attachment;filename=record.xlsx");

        EasyExcel.write(response.getOutputStream(),SysCallogsEntity.class).sheet("录音记录").doWrite(list);

        /*List<List<String>> excelData = new ArrayList<>();
        //表头
        List<String> head = new ArrayList<>();
        //获取所有记录数据
        List<SysCallogsEntity> list = sysCalllogsService.queryAllLogs();
        //遍历记录数据
        for (int i = 0; i < list.size(); i++) {
            //获取每行显示的数据
            List<String> data = new ArrayList<>();
            data.add(list.get(i).getCallee());
            data.add(list.get(i).getCaller());
            data.add(list.get(i).getCalleeRingTime());
            data.add(list.get(i).getDuration());
            //将数据添加到excel中
            excelData.add(data);
        }
        //表头添加到excel
        excelData.add(head);
        String sheetName = "data";
        String fileName = "data.xlsx";
        //将数据导出
        ExcelUtil.exportExcel(response, excelData, sheetName, fileName, 15);*/
    }

    @RequestMapping("/statistics")
    @ResponseBody
    public R statistics(@RequestBody JSONObject json) {



        return R.ok();
    }
}
